package com.yboot.starter.common.core.web.validation;

import lombok.experimental.UtilityClass;

import javax.validation.*;
import java.util.Set;

@UtilityClass
public class ValidationUtil {

    /**
     * 默认{@link Validator} 对象
     */
    private static final Validator validator;

    static {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            validator = factory.getValidator();
        }
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static void validate(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> validate = validator.validate(object, groups);
        if (!validate.isEmpty()) {
            throw new ConstraintViolationException(validate);
        }
    }

}